﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using MeTalker.SDK.Core;
using MeTalker.Window.SDK.Core;
using MeTalker.Aide.Forms;
using MeTalker.Aide.data;
using System.Drawing;

namespace MeTalker.Aide
{
    internal class GuideService : GuideBase, IWorkMode
    {
        Timer mTimer;

        int period;

        public IWork Work { get; set; }

        Random random = new Random(100);

        Point basepoint;

        Point currpoint = new Point();

        int currCount = 0;

        bool initPoint = false;

        IDictionary<string, MessageBody> dictMsgs = new Dictionary<string, MessageBody>();

        string OLD_MSG = "";

        internal GuideService(ProcInfo proc, int period, IWork work, WorkModeCallBack callback)
            : this(proc, period, work)
        {
            this.WorkCallback = callback;
        }

        internal GuideService(ProcInfo proc, int period, IWork work)
            : base(proc)
        {
            UserConfig useConfig = null;
            foreach (var user in DataFactory.SystemConfig.UserConfigs)
            {
                if (user.Account.Equals(proc.Account))
                {
                    useConfig = user;
                    break;
                }
            }
            if (useConfig.GuideMenu == 0)
            {
                useConfig.GuideMenu = DataFactory.Menus.DefaultId;
            }

            foreach (var menu in DataFactory.Menus.Nodes)
            {
                if (useConfig.GuideMenu == menu.Id)
                {
                    this.Menu = menu;
                    break;
                }
            }

            _workMode = TalkerState.AutoMenuGuide;
            this.WorkProcess = proc;
            this.period = period;
            Work = work;

            hwndMain = proc.ChildhWnd;

            Init(proc);
        }

        void Handler(IntPtr hWnd)
        {
            try
            {

                string text = LibHelper.GetMessageText(hWnd);
                if (!string.IsNullOrEmpty(text))
                {
                    if (text.Equals(OLD_MSG))
                    {
                        return;
                    }
                    OLD_MSG = text;
                    //msg = msg.Replace("\r", "").Replace("\n", "").Trim();
                    string[] msgs = text.Replace(" ", "").Split(new char[] { '\r', '\n' });
                    int len = msgs.Length;
                    string msg_name = msgs[len - 3];
                    string msg = msgs[len - 1];
                    string SendName = msg_name.Substring(0, msg_name.IndexOf("("));
                    string ReceivTime = msg_name.Replace(SendName, "").Replace("(", "").Replace(")", "");
                    ReceivTime = ReceivTime.Substring(0, ReceivTime.Length - 1);
                    if (!WorkProcess.Alias.Equals(SendName) && !"系统消息".Equals(SendName))
                    {
                        if(UtilHelper.DEBUG)
                            Console.WriteLine("发送" + msg_name + "接收到了:" + msg);
                        msg = FindMenuMessage(SendName, ReceivTime, msg);
                        if (!string.IsNullOrEmpty(msg))
                        {
                            SendText(mainhWndContent, msg);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Error("菜单导购", ex);
            }
            finally {
                CloseSession();
            }
        }

        #region 继承
        TalkerState _workMode;
        public TalkerState WorkMode { get { return _workMode; } }
        void IWork.Refresh() { }

        public WorkModeCallBack WorkCallback { get; set; }

        public ProcInfo WorkProcess { get; set; }

        void IWorkMode.InitView()
        {

        }

        void IWorkMode.InitData()
        {

        }

        bool IWork.Start()
        {
            try
            {
                Thread.Sleep(1000);
                KeysetControl.SendMessage(mainhWndContent, 177, 0, -1);
                KeysetControl.SendMessage(mainhWndContent, 771, 0, -1);
                Handler(mainhWndResposneContent);
                CloseSession();
                if (mTimer != null)
                    mTimer.Dispose();
                mTimer = null;
                mTimer = new Timer(TimerCallback, null, 1000, period);
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Info(string.Format("{0}启动菜单导购模式", WorkProcess.Alias));
                Console.WriteLine(WorkProcess.Alias + "启动菜单导购模式");
                return true;
            }
            catch
            {
                return false;
            }
        }

        void IWork.Stop()
        {
            try
            {            
                if (mTimer != null)
                    mTimer.Dispose();
                mTimer = null;
                if (mTimerClose != null)
                    mTimerClose.Dispose();
                mTimerClose = null;
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Info(string.Format("{0}退出菜单导购模式", WorkProcess.Alias));
                Console.WriteLine(WorkProcess.Alias + "退出菜单导购模式");
                WindowControl.ShowWindow(hwndMain, WindowControl.SW_SHOW);
            }
            catch { }
            finally {
                WindowControl.ShowWindow(hwndMain, WindowControl.SW_SHOW);
            }
        }

        #endregion

        void CloseCallback(object sender)
        {
            try
            {
                IntPtr hwndMain = WindowControl.FindWindow(null, "系统提示");
                int pid;
                WindowControl.GetWindowThreadProcessId(hwndMain, out pid);
                if (pid == WorkProcess.Pid)
                {
                    if (UtilHelper.DEBUG)
                        MuchInfo.Logs.MILog.Info("关闭对话框");
                    int d = WindowControl.EnumChildWindows(hwndMain, FindhWndCloseAlter, 0);
                    if (d == 0)
                    {
                        WindowControl.SetForegroundWindow(hwndMain);
                        KeysetControl.keybd_event(13, 0, 0, 0);
                    }
                    MouseControl.MouseLeft(buttonHandle, 2, 2);
                }
                if (!DataFactory.SystemConfig.IsHiddenPlatform)
                {
                    if (!WindowControl.IsWindowVisible(this.hwndMain))
                    {
                        if (WorkCallback != null)
                        {
                            WorkCallback.BeginInvoke(this, null, MeTalker.Aide.Forms.TalkerState.Closed, null, null);
                        }
                    }
                }
            }
            catch { }
        }
        
        void TimerCallback(object sender)
        {
            try
            {
                lock (dictMsgs)
                {
                    if (WindowControl.IsWindowEnabled(buttonHandle))
                    {
                        WindowControl.EnumChildWindows(hwndMain, FindhWndCloseAlter, 0);
                        Handler(mainhWndResposneContent);
                    }
                    else
                    {
                        //WindowControl.GetCursorPos(ref currpoint);
                        //if (!initPoint)
                        //{
                        //    initPoint = true;
                        //    basepoint = currpoint;
                        //}
                        //else
                        //{
                        //    if (basepoint.X == currpoint.X && basepoint.Y == currpoint.Y)
                        //    {
                        //        currCount++;
                        //    }
                        //    else
                        //    {
                        //        basepoint = currpoint;
                        //    }
                        //}
                        //if (currCount > UtilHelper.MAX_COUNT)
                        //{
                        //    currCount = 0;
                        //    MouseControl.SetCursorPos(random.Next(), random.Next());
                        //}
                    }
                }
                if (DataFactory.SystemConfig.IsHiddenPlatform)
                {
                    if (WindowControl.IsWindowVisible(this.hwndMain))
                    {
                        WindowControl.ShowWindow(hwndMain, WindowControl.SW_HIDE);
                    }
                }
                else
                {
                    if (WindowControl.IsIconic(hwndMain))
                    {
                        WindowControl.ShowWindowAsync(hwndMain, WindowControl.SW_RESTORE);
                    }

                    if (!WindowControl.IsWindowVisible(this.hwndMain))
                    {
                        //StopGuide();
                        if (WorkCallback != null)
                        {
                            WorkCallback.BeginInvoke(this, null, MeTalker.Aide.Forms.TalkerState.Closed, null, null);
                        }
                    }
                }
            }
            catch
            {
            }
        }
    }
}